package mbsl.ui.dialogs;

import static mbsl.util.SWTUtils.Direction.down;
import static mbsl.util.SWTUtils.Direction.left;
import static mbsl.util.SWTUtils.Direction.right;
import static mbsl.util.SWTUtils.Direction.up;
import mbsl.util.SWTUtils;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Shell;

/**
 * A simple selection dialog.
 * <p>
 * The dialog is a {@link Dialog}, with a list from which the user can select an item.
 */
public class Selector extends Dialog<Integer> {
	/**
	 * Sets up a very simple selector.
	 * @param pParent The parent window to which this dialog will be modal.
	 * @param pElements The List of elements to use in the dialog.  Text will be extracted using toString().  
	 * @param pMessage The message to show in the dialog.
	 * @param pHeader The title of the dialog.
	 */
	public Selector(Shell pParent, java.util.List<?> pElements, String pMessage, String pHeader) {
		super(pParent, pMessage, pHeader);
		
		for (Object object : pElements)
			mList.add(object.toString());
	}
	
	protected void addComponents(Shell pWindow, Label pLabel, final Button pConfirm) {
		pConfirm.setEnabled(false);
		
		mList = new List(pWindow, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL);
		
		mList.setLayoutData(SWTUtils.getFormData(300, 100,
				SWTUtils.getMeta(left, 0, 2),
				SWTUtils.getMeta(right, 100, -2),
				SWTUtils.getMeta(up, pLabel, 5),
				SWTUtils.getMeta(down, pConfirm, -5)
		));
		// Listeners
		mList.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent pE) {
				pConfirm.setEnabled(mList.getSelectionCount() > 0);
			}
			public void widgetDefaultSelected(SelectionEvent pE) {
				pConfirm.notifyListeners(SWT.Selection, new Event());
			}
		});
		// Routes the event to the confirm button listener if enter is pressed
		mList.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent pE) {
				if (pE.character == SWT.CR)
					pConfirm.notifyListeners(SWT.Selection, new Event());
			}
		});
		pWindow.addShellListener(new ShellAdapter() {
			public void shellClosed(ShellEvent pE) {
				close(null);
			}
		});
		pConfirm.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent pE) {
				if (pConfirm.isEnabled())
					if (mList.getSelectionIndex() > -1)
						close(mList.getSelectionIndex());
					else
						close(null);
			}
		});
		
		mList.forceFocus();
	}
	
	private List mList;
}
